import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '../store'
import {
  getToken,
  getUserId
} from '@/utils/auth'

// 创建axios实例
// const url = 'http://127.0.0.1:8000/hydra/'
// const url = 'http://hydra.xyz115.com:12345/hydra/'
// const url = 'http://103.230.240.50:12345/hydra/'
const url = window.location.origin + '/hydra/'
const service = axios.create( {
  // baseURL: process.env.BASE_API + 'hydra/', // api的base_url
  baseURL: url, // api的base_url
  timeout: 60000 // 请求超时时间
  // withCredentials: true // 允许携带cookie
} )

// request拦截器
service.interceptors.request.use( config => {  
  if ( store.getters.token ) {    
    // config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers[ 'HTTP_X_AUTH_USER' ] = getUserId()
      config.headers[ 'HTTP_X_AUTH_TOKEN' ] = getToken()          
      config.headers[ 'USERPROFILE' ] = JSON.stringify({user_id: getUserId(), token: getToken()})
  }
  return config
}, error => {
  // Do something with request error
  console.log( error ) // for debug
  Promise.reject( error )
} )

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * status为非0是抛错 可结合自己业务进行修改
     */
    // const res = response.data
    // if (res.status !== 0) {
    //   Message({
    //     message: '服务器错误',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   debugger
    //   return Promise.reject('error')
    // } else {
    //   return response.data
    // } 
    return response.data
  },
  error => {
    console.log( 'err' + error ) // for debug
    if ( error.response.data.msg ) {
      Message( {
        message: error.response.data.msg,
        type: 'error'
      } )
    } else {
      Message( {
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      } )
    }
    return Promise.reject( error )
  }
)

export default service
